//
//  TMURLShortenMacro.m
//  TMURLShorten
//
//  Created by Anshu Chimala on 1/3/10.
//  Copyright 2010 Home. All rights reserved.
//

#import "TMURLShortenMacro.h"
#import "HTTPOperation.h"

@implementation TMURLShortenMacro
@synthesize delegate = _delegate;

- (NSString *)title {
	return @"Create is.gd URL";
}

- (NSString *)author {
	return @"Anshu Chimala";
}

- (NSString *)description {
	return @"Creates a shortened URL out of a URL you've copied. (Powered by is.gd)";
}

- (NSString *)progressMessage {
	return @"Shortening URL...";
}

- (NSString *)beforeText {
	return @"http://www.airpoke.com/index.php";
}

- (NSString *)afterText {
	return @"http://is.gd/5LgNz";
}

- (void)processText:(NSString *)text {
	// This is a good example of how to create macros
	// that take time and require the progress screen.
	
	text=[text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	
	if(!text.length) {
		[_delegate macro:self didFailWithErrorMessage:@"Please copy a valid URL to shorten."];
		return;
	}
	
	_delegate.showActivityIndicator = YES;
	_delegate.shouldPasteAfterwards = YES;
	
	if(_queue)
		[_queue release], _queue = nil;
	_queue = [[NSOperationQueue alloc] init];
	
	NSString *url = [@"http://is.gd/api.php?longurl=" stringByAppendingString:text];
	
	// Feel free to use my HTTPOperation class in your own code
	// (or just use NSURLConnection).
	
	HTTPOperation *hop = [[HTTPOperation alloc] init];
	[hop setDelegate:self];
	[hop setSuccessSelector:@selector(httpSuccess:)];
	[hop setFailureSelector:@selector(httpFailure:)];
	[hop setTargetURL:[NSURL URLWithString:url]];
	[_queue addOperation:hop];
	[hop release];
}

- (void)httpSuccess:(NSData *)data {
	_delegate.showActivityIndicator = NO;
	NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
	[_delegate macro:self didProcessTextWithResult:str];
}

- (void)httpFailure:(NSError *)err {
	_delegate.showActivityIndicator = NO;
	[_delegate macro:self didFailWithErrorMessage:[err localizedDescription]];
}

@end
